//
// Created by Administrator on 2023/4/11.
//

#ifndef WEBRTC_MODEL_SENDERANALYZE_H
#define WEBRTC_MODEL_SENDERANALYZE_H

#include <bits/stdc++.h>

using namespace std;

struct SendPacket {
    long long sequenceNumber;
    long long sendTimestamp;
    long long captureTimestamp;
    int packetSize;

    SendPacket(long long int sequenceNumber, long long int sendTimestamp, long long int captureTimestamp,
               int packetSize) : sequenceNumber(sequenceNumber), sendTimestamp(sendTimestamp),
                                 captureTimestamp(captureTimestamp), packetSize(packetSize) {}
};

class SendAnalyze {
private:
    //发送数据包对象列表
    vector<SendPacket> sendPacketList;
public:
    const vector<SendPacket> &getSendPacketList() const {
        return sendPacketList;
    }
    SendAnalyze() {
        //输入发送数据包的数据
        inputSendPacketList();
    }

    //计算平均每5ms发送多少个数据包
    void computeSendPacketsPerTime() {
        //每个时间戳发送的数据包的数量
        unordered_map<long long, int> everySendPacketCount;
        //每个数据包数量的比例
        unordered_map<int, int> packetCountDistribution;
        //统计每次发送多少数据包
        for (const auto &sendPacket: sendPacketList){
            everySendPacketCount[sendPacket.sendTimestamp]++;
        }

        for (const auto &item: everySendPacketCount) {
            packetCountDistribution[item.second]++;
        }
        //发送次数
        auto timeCount = static_cast<double>(everySendPacketCount.size());
        ofstream everyTimeSendPacketDistribution;
        everyTimeSendPacketDistribution.open("log/everyTimeSendPacketDistribution.csv", ios::out | ios::app);

        for (const auto &item: packetCountDistribution) {
            everyTimeSendPacketDistribution << item.first << "," << (double) item.second / timeCount << endl;
        }
    }

    void inputSendPacketList() {
        long long sequenceNumber_;
        long long sendTimestamp_;
        long long captureTimestamp_;
        int packetSize_;
        ifstream sendPacketLog;
        sendPacketLog.open("log/sendPacket.log", ios::in);
        while (sendPacketLog >> sequenceNumber_ >> sendTimestamp_ >> captureTimestamp_ >> packetSize_) {
            sendPacketList.emplace_back(sendTimestamp_, sendTimestamp_, captureTimestamp_, packetSize_);
        }
    }

    //累加得出小于某个值的概率
    static void getJitterCDFLessThan(int x) {
        ifstream jitterDistributionInput;
        jitterDistributionInput.open("log/jitterDistribution.csv", ios::in);
        int jitter_;
        double probability_;
        double result = 0;
        while (jitterDistributionInput >> jitter_ >> probability_) {
            if (jitter_ <= x) { result += probability_; }
        }
        cout << result << endl;
    }
};

#endif //WEBRTC_MODEL_SENDERANALYZE_H
